package com.fanyue.modules.wzb.controller.admin;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.fanyue.core.annotation.CoolRestController;
import com.fanyue.core.exception.CoolPreconditions;
import com.fanyue.core.request.R;
import com.fanyue.core.util.CoolSecurityUtil;
import com.fanyue.modules.base.entity.sys.BaseSysUserEntity;
import com.fanyue.modules.base.service.sys.BaseSysUserService;
import com.fanyue.modules.wzb.entity.*;
import com.fanyue.modules.wzb.service.*;
import com.fanyue.modules.wzb.utils.ChipReadingUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestAttribute;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequiredArgsConstructor
@Tag(name = "用户信息", description = "用户信息")
@CoolRestController
public class ChipReadingController {

    private final ClothingInfoService clothingInfoService;
    private final ClothingSpecService clothingSpecService;
    private final ClothingBatchItemService clothingBatchItemService;
    private final CargoService cargoService;
    private final AppUserFaceRecordService appUserFaceRecordService;
    private final AppUserService appUserService;
    private final BaseSysUserService sysUserService;

    @Operation(summary = "读取芯片")
    @PostMapping("/code")
    public R code(@RequestAttribute JSONObject requestParams) {
        /*ChipReadingUtils.setKaiguan(true);
        String code = ChipReadingUtils.code();*/
        String code = requestParams.getStr("code");
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        if (StrUtil.isNotEmpty(code)) {
            ClothingInfoEntity clothing = new ClothingInfoEntity();
            clothing.setCode(code);
            List<ClothingInfoEntity> clothingList = clothingInfoService.listByInfo(clothing);
            CoolPreconditions.check(clothingList.size() > 0, "编号已存在");
        }
        return R.ok().put("data", map);
    }

    @Operation(summary = "读取芯片信息")
    @PostMapping("/clothing")
    public R clothing(@RequestAttribute JSONObject requestParams) {
        //后台系统用户不校验
        JSONObject tokenInfo = CoolSecurityUtil.getAdminUserInfo(requestParams);
        BaseSysUserEntity sysUser = sysUserService.getById(tokenInfo.get("userId").toString());

        /*ChipReadingUtils.setKaiguan(true);
        String code = ChipReadingUtils.code();*/
        String code = requestParams.getStr("code");
        if (StrUtil.isNotEmpty(code)) {
            ClothingInfoEntity clothingInfo = clothingInfoService.getByCode(code);
            CoolPreconditions.check(ObjectUtil.isEmpty(clothingInfo), "芯片未录入系统");
            if (sysUser.getType() == 1) {
                Long recordId = requestParams.getLong("recordId");
                if (recordId != null) {
                    CoolPreconditions.check(!recordId.equals(clothingInfo.getFaceRecordId()), "你没有权限处理该被装");
                }
                //更新record时间
                AppUserFaceRecordEntity recordEntity = appUserFaceRecordService.getById(recordId);
                if (ObjectUtil.isNotEmpty(recordEntity)) {
                    recordEntity.setUpdateTime(new Date());
                    appUserFaceRecordService.updateById(recordEntity);
                }
            } else {
                //0-信息读取，1-外部借出，2-外部归还，5-上架，6-下架
                Integer type = requestParams.getInt("type");
                CoolPreconditions.check(type == null || (type != 0 && type != 1 && type != 2 && type != 5 && type != 6), "参数类型错误");

                if (type == 2 && clothingInfo.getStatus() == 4) {
                    ClothingBatchItemEntity selectBatchItem = new ClothingBatchItemEntity();
                    Long batchId = requestParams.getLong("batchId");
                    selectBatchItem.setBatchId(batchId);
                    selectBatchItem.setClothingId(clothingInfo.getId());
                    List<ClothingBatchItemEntity> batchItemList = clothingBatchItemService.listByInfo(selectBatchItem);
                    if (batchItemList.size() == 0) {
                        return R.error("当前被装不属于当前批次");
                    }
                    //分配货架，并锁定，
                    clothingInfo = appUserFaceRecordService.distributionByRevert(clothingInfo);
                }
                if (type == 5) {
                    if (clothingInfo.getStatus() != 0 && clothingInfo.getStatus() != 9) {
                        String msg = "当前被装";
                        if (clothingInfo.getStatus() == 1) msg += "已上架";
                        if (clothingInfo.getStatus() == 2) msg += "已借出";
                        if (clothingInfo.getStatus() == 3) msg += "已损坏";
                        if (clothingInfo.getStatus() == 4) msg += "已外借";
                        return R.error(msg);
                    }
                    //分配货架，并锁定，
                    clothingInfo = appUserFaceRecordService.distributionByRevert(clothingInfo);
                }
                if (type == 6) {
                    if (clothingInfo.getStatus() != 1) {
                        String msg = "当前被装不在库";
                        return R.error(msg);
                    }
                }
                //货位信息
                if (clothingInfo.getStatus() != 0) {
                    CargoEntity cargoEntity = cargoService.getById(clothingInfo.getCargoId());
                    if (ObjectUtil.isNotEmpty(cargoEntity)) {
                        clothingInfo.setCargoPosition(cargoEntity.getPosition());
                    } else {
                        clothingInfo.setCargoPosition("无货架信息");
                    }
                }
            }
            if (clothingInfo.getSpecId() != null) {
                ClothingSpecEntity specEntity = clothingSpecService.getById(clothingInfo.getSpecId());
                if (ObjectUtil.isNotEmpty(specEntity)) {
                    clothingInfo.setSpecName(specEntity.getName());
                }
            }
            return R.ok().put("data",clothingInfo);
        }
        return R.error("请识别被装芯片");
    }

    @Operation(summary = "关闭识别")
    @GetMapping("/close")
    public R close() {
        ChipReadingUtils.setKaiguan(false);
        return R.ok();
    }
}
